package com.aoxiang.zbox.config;

import com.aoxiang.zbox.common.exception.BaseException;
import com.aoxiang.zbox.common.exception.ErrorCodeEnum;
import com.aoxiang.zbox.common.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 参数校验异常
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<String> handleBindException(BindException ex) {
        LOGGER.error("参数缺失错误: ", ex);
        StringBuilder errorMessages = new StringBuilder();
        for (FieldError fieldError : ex.getFieldErrors()) {
            errorMessages.append(fieldError.getField())
                    .append(": ")
                    .append(fieldError.getDefaultMessage())
                    .append("; ");
        }
        // 返回包含所有错误消息的Result
        return Result.error(ErrorCodeEnum.PARAM_MISSING.getCode(), errorMessages.toString());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        LOGGER.error("请求参数错误: ", ex);
        return Result.error(ErrorCodeEnum.PARAM_MISSING.getCode(), "请求参数错误");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        LOGGER.info("请求方式错误: ", ex);
        return Result.error(ErrorCodeEnum.REQUEST_METHOD_ERROR);
    }

    // 自定义异常
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public Result<String> handleException(BaseException ex) {
        LOGGER.info("BaseException: ", ex);
        return Result.error(ex);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<String> handleException(Exception ex) {
        LOGGER.error("Exception: ", ex);
        return Result.error(ErrorCodeEnum.SYSTEM_ERROR);
    }

}
